package com.example.testlxr9096.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.testlxr9096.R;
import com.example.testlxr9096.ThrottleOnItemClickListener;
import com.example.testlxr9096.bean.IoItem;

import java.util.List;

public  class IoAdapter extends RecyclerView.Adapter<IoAdapter.ViewHolder> {

    private final List<IoItem> ioItems;
    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public IoAdapter(List<IoItem> ioItems) {
        this.ioItems = ioItems;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_io, parent, false);
        return new ViewHolder(view);
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        IoItem item = ioItems.get(position);
        holder.ioName.setText(item.getName());

        // 根据选中状态设置背景
        holder.itemView.setSelected(item.isSelected());

        holder.itemView.setOnClickListener(new ThrottleOnItemClickListener() {
            @Override
            public void onThrottleClick(View v) {
                // 处理点击事件
                int pos = holder.getAdapterPosition();
                if (pos != RecyclerView.NO_POSITION) {
                    if (listener != null) {
                        listener.onItemClick(position);
                    }
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return ioItems.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView ioName;

        public ViewHolder(View itemView) {
            super(itemView);
            ioName = itemView.findViewById(R.id.io_name);
        }
    }
}